package slw.utils
{
	import flash.utils.ByteArray;
	
	/**
	 * Base64
	 * 字符串编码类
	 * @author ddx<br/>
	 * 2011-6-16
	 *
	 */
	public class Base64
	{
		//
		private static const CHARACTERS:String="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-=";
		/**
		 * 构造函数
		 * 
		 */
		public function Base64()
		{
			throw new Error("Base64 是一个静态类.");
		}
		/*
		-----------------------------------
		public  methods
		-----------------------------------
		*/
		//
		/**
		 * 将字符串编码为 Base64 格式字符串
		 * @param data:String
		 * @return String
		 * 
		 */		
		public static function encode(data:String):String{//11111111 11111111 11111111 
			var $bytes:ByteArray=new ByteArray();
			$bytes.writeUTFBytes(data);
			
			return encodeByteArray($bytes);
		}
		//
		/**
		 * 将ByteArray编码为字符串
		 * @param data:ByteArray
		 * @return String
		 * 
		 */		
		public static function encodeByteArray(data:ByteArray):String{
			var $bytes:ByteArray=data;
			$bytes.position=0;
			
			var $result:String="";
			var $array:Array=new Array(4);
			while($bytes.bytesAvailable>0){
				var $buffer:ByteArray=new ByteArray();
				for(var i:int=0;i<3&&$bytes.bytesAvailable>0;i++){
					$buffer[i]=$bytes.readUnsignedByte();
				}
				
				$array[0]=($buffer[0]&0xfc)>>2;
				$array[1]=(($buffer[0]&0x3)<<4)|(($buffer[1]&0xf0)>>4);
				$array[2]=(($buffer[1]&0xf)<<2)|(($buffer[2]&0xc0)>>6);
				$array[3]=$buffer[2]&0x3f;
				
				for(i=0;i<4;i++){
					$array[i]=$buffer.length>=i?$array[i]:CHARACTERS.length-1;
					$result+=CHARACTERS.charAt($array[i]);
				}
			}
			
			return $result;
		}
		//
		/**
		 * 将Base64 格式 的字符串解码为原始字符串
		 * @param data:String
		 * @return String
		 * 
		 */		
		public static function decode(data:String):String{//111111 111111 111111 111111 
			var $buffer:ByteArray=decodeToByteArray(data);
			$buffer.position=0;
			
			return $buffer.readUTFBytes($buffer.length);
		}
		//
		/**
		 * 将Base64 格式 的字符串解码为ByteArray 
		 * @param data:String
		 * @return ByteArray
		 * 
		 */		
		public static function decodeToByteArray(data:String):ByteArray{
			var $array:Array=[];
			var $cache:Array=[];
			var $buffer:ByteArray=new ByteArray();
			for(var i:int=0;i<data.length;i+=4){
				var $part:String=data.substr(i,4);
				for(var j:int=0;j<$part.length;j++){
					$array[j]=CHARACTERS.indexOf($part.charAt(j));
				}
				
				$cache[0]=($array[0]<<2)|($array[1]>>4);
				$cache[1]=(($array[1]&0xf)<<4)|($array[2]>>2);
				$cache[2]=(($array[2]&0x3)<<6)|$array[3];
				
				for(var k:int=0;k<$cache.length;k++){
					if($array[k+1]==CHARACTERS.length-1) break;
					$buffer.writeByte($cache[k]);
				}
			}
			
			return $buffer;
		}
		/*
		-----------------------------------
		private  methods
		-----------------------------------
		*/
		
	}
}